package nav

import (
	"gin-project-01/gin-step04/gin15-gorm-advance/controllers"
	myModel "gin-project-01/gin-step04/gin15-gorm-advance/models"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type NavController struct {
	controllers.BaseController //继承 controllers.BaseController
}

// Index
//
//	@Description: 查询所有
//	@receiver con
//	@param c
func (con NavController) Index(c *gin.Context) {
	var navList []myModel.Nav
	myModel.Db.Find(&navList)
	c.JSON(http.StatusOK, myModel.Success("查询成功", navList))
}

// GetById
//
//	@Description:  http://localhost:8888/nav/get/4  动态路由的方式传参
//	@receiver con
//	@param c
func (con NavController) GetById(c *gin.Context) {
	param := c.Param("id")
	id, _ := strconv.Atoi(param)
	var nav myModel.Nav
	myModel.Db.Where("id=?", id).Find(&nav)
	if nav.Id == 0 {
		c.JSON(http.StatusOK, myModel.Success("查询成功", nil))
		return
	}
	c.JSON(http.StatusOK, myModel.Success("查询成功", nav))
}

//
// Select
//  @Description: 条件查询 http://localhost:8888/nav/get
//  @receiver con
//  @param c
//

func (con NavController) Select(c *gin.Context) {
	var navList []myModel.Nav
	//查询id > 3
	myModel.Db.Where("id > ?", 3).Find(&navList)

	//查询id > 3 && id <9
	myModel.Db.Where("id > ? and id < ?", 3, 9).Find(&navList)

	//查询 id in 1,2,3,4
	myModel.Db.Where("id in (?,?,?,?)", 1, 2, 3, 4).Find(&navList)
	myModel.Db.Where("id in ?", []int{1, 2, 3, 4}).Find(&navList) //推荐

	//查询 title like '%会%'
	myModel.Db.Where("title like ?", "%会%").Find(&navList)

	//查询 id between 3 and 9
	myModel.Db.Where("id between ? and ?", 3, 9).Find(&navList)

	//查询 id =2 or id=3
	myModel.Db.Where("id =? or id=?", 2, 3).Find(&navList)
	myModel.Db.Where("id = ?", 2).Or("id = ?", 3).Or("id = ?", 4).Find(&navList)

	//查询-指定返回的字段,这里使用的时临结构体
	var navJsonList []myModel.NavJson
	myModel.Db.Select("id,title").Where("id > ?", 3).Find(&navJsonList)
	c.JSON(http.StatusOK, myModel.Success("查询成功", navJsonList))

	//查询 order排序
	myModel.Db.Where("id > ?", 3).Order("id desc").Find(&navList)

	//查询 offset(跳过) limit
	myModel.Db.Offset(1).Limit(2).Order("id asc").Find(&navList)

	//查询 统计数量
	var count int64
	myModel.Db.Find(&navList).Count(&count)
	c.JSON(http.StatusOK, myModel.Success("查询成功", count))

	c.JSON(http.StatusOK, myModel.Success("查询成功", navList))
}

// Raw
//
//	@Description: 使用原生sql
//	@receiver n
//	@param c
func (n NavController) Raw(c *gin.Context) {
	var navList []myModel.Nav
	//删除
	myModel.Db.Raw("delete from nav where id = ?", 5)

	//修改
	myModel.Db.Raw("update nav set title = ? where id = ?", "会员企业1", 4)

	//增加
	myModel.Db.Exec("insert into nav(title,url,sort,status) values(?,?,?,?)", "友情链接", "http://www.baidu.com", 11, 1)

	//查询
	myModel.Db.Raw("select * from nav where id > ?", 3).Scan(&navList)

	//查询
	var count int64
	myModel.Db.Raw("select count(*) from nav where id  > ?", 3).Scan(&count)
	c.JSON(http.StatusOK, myModel.Success("操作成功", count))

	c.JSON(http.StatusOK, myModel.Success("操作成功", navList))

}
